package com.it.schoolbookshop_back.service.impl;

import com.it.schoolbookshop_back.entities.dto.SettingsResponseDTO;
import com.it.schoolbookshop_back.entities.dto.UpdateSettingsDTO;
import com.it.schoolbookshop_back.entities.po.Settings;
import com.it.schoolbookshop_back.mapper.AdminSettingsMapper;
import com.it.schoolbookshop_back.service.AdminSettingsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统设置服务实现类
 */
@Service
public class AdminSettingsServiceImpl implements AdminSettingsService {
    
    private static final Logger log = LoggerFactory.getLogger(AdminSettingsServiceImpl.class);
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    @Autowired
    private AdminSettingsMapper adminSettingsMapper;
    
    @Override
    public List<SettingsResponseDTO> getAllSettings() {
        try {
            // 获取所有系统设置
            List<Settings> settingsList = adminSettingsMapper.getAllSettings();
            List<SettingsResponseDTO> responseDTOList = new ArrayList<>();
            
            // 转换为响应DTO
            for (Settings settings : settingsList) {
                SettingsResponseDTO responseDTO = new SettingsResponseDTO();
                responseDTO.setId(settings.getId());
                responseDTO.setSetting_key(settings.getSettingKey());
                // 将整数值转换为字符串
                responseDTO.setValue(String.valueOf(settings.getValue()));
                responseDTO.setDescription(settings.getDescription());
                // 格式化日期时间
                responseDTO.setUpdated_at(settings.getUpdatedAt() != null ? 
                        settings.getUpdatedAt().format(formatter) : null);
                
                responseDTOList.add(responseDTO);
            }
            
            log.info("成功获取系统设置，共{}条记录", responseDTOList.size());
            return responseDTOList;
        } catch (Exception e) {
            log.error("获取系统设置失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }
    
    @Override
    @Transactional
    public boolean updateSettings(UpdateSettingsDTO updateSettingsDTO) {
        if (updateSettingsDTO == null || updateSettingsDTO.getSettings() == null || updateSettingsDTO.getSettings().isEmpty()) {
            log.warn("更新设置请求为空或无有效设置项");
            return false;
        }
        
        try {
            int successCount = 0;
            
            // 遍历要更新的设置项
            for (UpdateSettingsDTO.SettingItem item : updateSettingsDTO.getSettings()) {
                if (item.getId() == null || item.getValue() == null) {
                    log.warn("设置项ID或value为空，跳过");
                    continue;
                }
                
                // 检查设置是否存在
                Settings existingSetting = adminSettingsMapper.getSettingById(item.getId());
                
                if (existingSetting != null) {
                    // 更新设置
                    int result = adminSettingsMapper.updateSettingById(
                            item.getId(), 
                            item.getValue(), 
                            item.getDescription()
                    );
                    
                    if (result > 0) {
                        successCount++;
                        log.info("更新设置成功: ID={}, value={}, description={}",
                                item.getId(), item.getValue(), item.getDescription());
                    } else {
                        log.warn("更新设置失败: ID={}, value={}, description={}",
                                item.getId(), item.getValue(), item.getDescription());
                    }
                } else {
                    log.warn("找不到ID={}的设置项，跳过", item.getId());
                }
            }
            
            log.info("设置更新完成，成功{}项，总计{}项", successCount, updateSettingsDTO.getSettings().size());
            return successCount > 0;
            
        } catch (Exception e) {
            log.error("更新系统设置失败: {}", e.getMessage(), e);
            // 事务会自动回滚
            return false;
        }
    }
}
